/*
 * MessageFormController.java
 *
 * Created on December 29, 2008, 7:01 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.vacuela.publishmx.web.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.util.WebUtils;
import org.vacuela.publishmx.constant.Constants;
import org.vacuela.publishmx.context.ServiceContext;
import org.vacuela.publishmx.context.ServiceContextImpl;
import org.vacuela.publishmx.domains.Message;
import org.vacuela.publishmx.services.ContactBookService;
import org.vacuela.publishmx.services.MessagingService;
import org.vacuela.publishmx.web.bean.MessageForm;
import org.vacuela.publishmx.web.bean.UserSession;

/**
 *
 * @author nestor.carrasco
 */
public class MessageFormController extends SimpleFormController {
    
    private ContactBookService bookSvc;
    private MessagingService msgSvc;
    
    
    
    public MessageFormController() {
        setSessionForm(true);
        setValidateOnBinding(false);
        setCommandName("messageForm");
        setFormView("messages/messageForm");
    }
    
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        return new MessageForm();
    }
    
    protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors)
    throws Exception {
        
        MessageForm messageForm = (MessageForm) command;
        Message message = messageForm.getMessage();
        
        
        if ((messageForm.getIndividualNumbers() == null || "".equals(messageForm.getIndividualNumbers()))
        &&
                (messageForm.getAgendaNumbers() == null || "".equals(messageForm.getAgendaNumbers()))
                ){
            errors.rejectValue( "individualNumbers","MESSAGE_NUMBERS_REQUIRED",
                    "Please type any phone number .");
        }
    
        if (message.getText() == null || "".equals(message.getText())){
             errors.rejectValue( "individualNumbers","MESSAGE_TEXT_REQUIRED",
                    "Please type any Text .");
        }
    }
    
    protected ModelAndView onSubmit(
            HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)
            throws Exception {
        UserSession userSession = (UserSession)WebUtils.getRequiredSessionAttribute(request,Constants.USER_SESSION_DATA);
        
        MessageForm messageForm = (MessageForm) command;
        Message message = messageForm.getMessage();
         if ((messageForm.getIndividualNumbers() != null && !"".equals(messageForm.getIndividualNumbers()))){
            message.setIndPhoneNumbers(StringUtils.split(messageForm.getIndividualNumbers(),","));
          }
        
        if ((messageForm.getAgendaNumbers() != null && !"".equals(messageForm.getAgendaNumbers()))){
            message.setContactIds(StringUtils.split(messageForm.getAgendaNumbers(),","));
        }
        
        message.setUserId(userSession.getUserDomain().getId());
        message.setTypeMsg(Constants.OUT_MSG_TYPE);
        message.setPriority(Constants.MSG_LOW_PRIORITY);
        ServiceContext context = new ServiceContextImpl();
        context.setAttribute("messageDomain", message);
        
        
        try {    
              msgSvc.saveUpdateMessage(context);       
        } catch (DataIntegrityViolationException ex) {
             errors.rejectValue( "individualNumbers","MESSAGE_NUMBERS_REQUIRED",
                    "Any Error was raised when savind the messages.");
            return showForm(request, response, errors);
        }
        
        return super.onSubmit(request, response, command, errors);
    }
    
    public void setContactBookService(ContactBookService svc){
        this.bookSvc = svc;
    }
    
    public void setMessagingService(MessagingService svc){
        this.msgSvc = svc;
    }
}
